# main.py
import uvicorn
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
import asyncio
import logging
import urllib.request
from urllib.parse import quote
from lxml import etree
import json

from dj import getFromDuanJu, pushToNc, getVideos

# uvicorn main:app --reload

# 配置日志记录
logging.basicConfig(
    level=logging.INFO,
    filename="app.log",  # 指定日志文件路径和名称
    filemode="a",  # 使用追加模式，将日志写入到文件末尾
    format="%(asctime)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)

app = FastAPI()
templates = Jinja2Templates(directory="templates")

@app.get("/htm", response_class=HTMLResponse)
def index(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})

@app.get("/")
async def read_root():
    return {"message": "你瞅啥"}
    
@app.get("/dj/videos")
async def videos():
    videos = await getVideos()
    return videos
    
@app.get("/dj/search/{djName}")  
async def get_dj(djName: str):
    videos = await getFromDuanJu(djName)
        
    return {"list": videos}
    
@app.get("/dj/push")  
async def get_dj():
    result = await pushToNc()
        
    return {"list": result}

# 提供升级检测的接口
@app.get("/check_update")
async def check_update():
    # 在这里实现升级检测的逻辑，比如请求服务器获取最新版本信息等
    return {"update_available": True, "latest_version": "1.0.1"}
    
# 下载远程新版本exe并重启应用
@app.get("/update_app")
async def update_app():
    # 下载远程新版本exe文件
    # 这里假设下载成功，并将新版本exe保存为new_app.exe
    # await execute_command("wget -O new_app.exe http://720.local/aa.exe")
    
    # 下载远程新版本exe文件
    url = "http://720.local/aa.exe"
    filename = "new_app.exe"
    urllib.request.urlretrieve(url, filename)

    # 停止当前运行的exe
    await execute_command("taskkill /F /IM app.exe")

    # 重命名
    await execute_command("ren new_app.exe app.exe")

    # 启动新版本exe
    await execute_command("start app.exe")

    return {"message": "Update completed"}

async def execute_command(command: str):
    logger.info(f"Executing command: {command}")
    process = await asyncio.create_subprocess_shell(
        command,
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE
    )
    stdout, stderr = await process.communicate()
    logger.info(f"Command output (stdout): {stdout.decode()}")
    logger.info(f"Command output (stderr): {stderr.decode()}")

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)